package cc.angis.xiugallery.account;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Toast;
import cc.angis.xiugallery.R;
import cc.angis.xiugallery.UserAccountActivity;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.data.CommentData;
import cc.angis.xiugallery.data.UserAccount;
import cc.angis.xiugallery.db.CommentDBHelper;
import cc.angis.xiugallery.db.FavouriteDBHelper;
import cc.angis.xiugallery.db.FavouriteImagesDBHelper;
import cc.angis.xiugallery.db.PostDBHelper;
import cc.angis.xiugallery.db.PostPlatformDBHelper;
import cc.angis.xiugallery.db.TableConstants;
import cc.angis.xiugallery.db.UserAccountDBHelper;

import com.weibo.net.AccessToken;
import com.weibo.net.AsyncWeiboRunner;
import com.weibo.net.AsyncWeiboRunner.RequestListener;
import com.weibo.net.DialogError;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

public class WeiboAccountManager implements IAccountManager {
	
	private Context context;
	
	public WeiboAccountManager(){
		
	}
	
	public WeiboAccountManager(Context context){
		this.context = context;
	}

	@Override
	public void doAuth() {
		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(GlobalConst.CONSUMER_KEY, GlobalConst.CONSUMER_SECRET);
		// Oauth2.0
		// 隐式授权认证方式
		weibo.setRedirectUrl("https://api.weibo.com/oauth2/default.html");// 此处回调页内容应该替换为与appkey对应的应用回调页
		// 对应的应用回调页可在开发者登陆新浪微博开发平台之后，
		// 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看，
		// 应用回调页不可为空
		weibo.authorize((Activity)context,
				new AuthDialogListener());

	}
	
	class AuthDialogListener implements WeiboDialogListener {

		@Override
		public void onComplete(Bundle values) {
			final String token = values.getString("access_token");
			final String expires_in = values.getString("expires_in");
			final String uid = values.getString("uid");
			AccessToken accessToken = new AccessToken(token, GlobalConst.CONSUMER_SECRET);
			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);
			AsyncWeiboRunner runner  = new AsyncWeiboRunner(Weibo.getInstance());
			WeiboParameters parameters = new WeiboParameters();
			parameters.add("access_token", token);
			parameters.add("uid", uid);
			
			runner.request(context, "https://api.weibo.com/2/users/show.json", parameters, "GET", new RequestListener() {
				
				@Override
				public void onIOException(IOException e) {
					e.printStackTrace();
				}
				
				@Override
				public void onError(WeiboException e) {
					e.printStackTrace();
				}
				
				@Override
				public void onComplete(String response) {
					UserAccountDBHelper dbHelper  = new UserAccountDBHelper(context, TableConstants.TABLE_USER_ACCOUNT);
					try {
						JSONObject object = new JSONObject(response);
						String username = object.getString("name");
						String avatar_url = object.getString("profile_image_url");
						if (!dbHelper.isExist(TableConstants.UserAccount.USER_ID, TableConstants.UserAccount.ACCOUNT_TYPE, uid, GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO+""))
							dbHelper.insert(uid, username, token, Long.parseLong(expires_in), GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO, avatar_url);
						else 
							dbHelper.update(uid, username, token, Long.parseLong(expires_in), GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO, avatar_url);
					} catch (JSONException e) {
						e.printStackTrace();
					} finally{
						dbHelper.closeDB();
					}
					if (context instanceof UserAccountActivity)
			        	((UserAccountActivity)context).onCreate(null);
				}
			});
		}

		@Override
		public void onError(DialogError e) {
		}

		@Override
		public void onCancel() {
		}

		@Override
		public void onWeiboException(WeiboException e) {
		}

	}

	@Override
	public void setContext(Context context) {
		this.context = context;
	}

	@Override
	public void sharePic(final UserAccount account, final String postId, final String content,
			final String imgPath) {
		AccessToken accessToken = new AccessToken(account.getAccessToken(), GlobalConst.CONSUMER_SECRET);
		accessToken.setExpiresIn(account.getExpiredIn());
		Weibo.getInstance().setAccessToken(accessToken);
		AsyncWeiboRunner runner  = new AsyncWeiboRunner(Weibo.getInstance());
		WeiboParameters parameters = new WeiboParameters();
		parameters.add("access_token", accessToken.getToken());
		try {
			parameters.add("status", URLEncoder.encode(content,"UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			parameters.add("status", content);

		}
		parameters.add("pic", imgPath);
		runner.request(context, "https://upload.api.weibo.com/2/statuses/upload.json", parameters, "POST", new RequestListener() {
			
			@Override
			public void onIOException(IOException e) {
				e.printStackTrace();
			}
			
			@Override
			public void onError(WeiboException e) {
				if(e.getStatusCode() == 21327){
					AlertDialog.Builder builder = new AlertDialog.Builder(context);
					builder.setTitle(R.string.dialog_tokenexpired_title).setMessage(R.string.dialog_tokenexpired_text)
					.setPositiveButton(R.string.dialog_authorize, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							doAuth();
						}

					}).setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							
						}

					}).show();
				}
			}
			
			@Override
			public void onComplete(String response) {
				PostPlatformDBHelper dbHelper = new PostPlatformDBHelper(context, TableConstants.TABLE_POST_PLATFORM);
				try{
					JSONObject object = new JSONObject(response);
					String platformId = String.valueOf(object.getLong("id"));
					dbHelper.insert(postId, platformId, GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO);
				} catch (Exception e){
					e.printStackTrace();
				} finally{
					dbHelper.closeDB();
				}
			}
		});
		
	}

	@Override
	public void retrieveComments(final UserAccount account, final String postId, String platformId) {
		String lastCommentId = "0";
		CommentDBHelper dbhelper = new CommentDBHelper(context, TableConstants.TABLE_COMMENT);
		try{
			CommentData lastComment = dbhelper.getLastCommentByType(GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO);
			if (lastComment !=null && lastComment.getCommentId()!=null)
				lastCommentId = lastComment.getCommentId();
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			dbhelper.closeDB();
		}
		AccessToken accessToken = new AccessToken(account.getAccessToken(), GlobalConst.CONSUMER_SECRET);
		accessToken.setExpiresIn(account.getExpiredIn());
		Weibo.getInstance().setAccessToken(accessToken);
		AsyncWeiboRunner runner  = new AsyncWeiboRunner(Weibo.getInstance());
		WeiboParameters parameters = new WeiboParameters();
		parameters.add("access_token", accessToken.getToken());
		parameters.add("id", platformId);
		parameters.add("since_id", lastCommentId);
		runner.request(context, "https://api.weibo.com/2/comments/show.json", parameters, "GET", new RequestListener() {
			
			@Override
			public void onIOException(IOException e) {
				e.printStackTrace();
			}
			
			@Override
			public void onError(WeiboException e) {
//				if("expired_token".equals(e.getMessage())){
//					doAuth();
//				}
			}
			
			@Override
			public void onComplete(String response) {
				CommentDBHelper dbHelper = new CommentDBHelper(context, TableConstants.TABLE_COMMENT);
				PostDBHelper pDbHelper = new PostDBHelper(context, TableConstants.TABLE_POST);
				try{
					JSONObject object = new JSONObject(response);
					JSONArray comments = object.getJSONArray("comments");
					JSONObject comment;
					for (int i=0; i<comments.length(); i++){
						comment = comments.getJSONObject(i);
						JSONObject user = comment.getJSONObject("user");
						SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzzzz yyyy", Locale.ENGLISH);
						long timestamp = formatter.parse(comment.getString("created_at")).getTime();
						if (!dbHelper.isExist(TableConstants.CommentColumn.COMMENT_ID, comment.getString("id")))
							dbHelper.insert(comment.getString("id"), postId, comment.getString("text"), user.getString("name"), user.getString("profile_image_url"), 
									timestamp, GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO);
						long postLastUpdate = pDbHelper.getPostLastUpdateByPostId(postId);
						if(postLastUpdate < formatter.parse(comment.getString("created_at")).getTime()){
							pDbHelper.update(postId, 0, timestamp);
						}
					}
					
				} catch (Exception e){
					e.printStackTrace();
				} finally{
					dbHelper.closeDB();
					pDbHelper.closeDB();
				}
			}
		});
		
	}

	@Override
	public void unbind() {
		UserAccountDBHelper dbHelper = new UserAccountDBHelper(context, TableConstants.TABLE_USER_ACCOUNT);
		try{
			dbHelper.deleteByType(GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO);
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			dbHelper.closeDB();
		}
	}


}
